package cn.ljy.uem.service.common;

import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.model.SysUser;
import cn.ljy.common.exception.model.MyForbiddenException;
import cn.ljy.common.exception.model.base.MyRollBackException;
import cn.ljy.uem.dao.*;
import cn.ljy.uem.model.SchoolConfig;
import cn.ljy.uem.model.SchoolStudent;
import cn.ljy.uem.model.SchoolTeacher;
import cn.ljy.uem.model.SchoolTeachingTaskLesson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 学校模块公共业务类的实现，用于提供给学校模块的其他业务类调用
 * @author ljy
 * 20221019
 */
@Service
@Validated
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Slf4j
public class CommonSchoolService {
    @Autowired
    private SchoolConfigMapper schoolConfigMapper;
    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;
    @Autowired
    private SchoolStudentMapper schoolStudentMapper;
    @Autowired
    private SchoolTeacherCourseMapper schoolTeacherCourseMapper;

    @Autowired
    private SchoolTeachingTaskLessonMapper schoolTeachingTaskLessonMapper;

    /**
     * 读取账户对应的教师信息
     * @param sysUser
     * @return
     */
    public SchoolTeacher getTeacher(@NotNull(message = "用户信息不能为空") SysUser sysUser){
        SchoolTeacher teacher=null;
        if(sysUser.getId()!=null){
            teacher=schoolTeacherMapper.getTeacherByUserId(sysUser.getId());
        }
        return teacher;
    }

    /**
     * 读取账户对应的教师信息
     * @param userId
     * @return
     */
    public SchoolTeacher getTeacherByUserId(@NotNull(message = "用户主键不能为空") Long userId){
        return schoolTeacherMapper.getTeacherByUserId(userId);
    }


    /**
     * 读取账户对应的教师信息
     * @return
     */
    public SchoolTeacher getLoginTeacher(){
        SchoolTeacher teacher=null;
        //获取当前登录信息
        SysUser sysUser = UserUtil.getLoginUser();
        if(sysUser.getId()!=null){
            teacher=schoolTeacherMapper.getTeacherByUserId(sysUser.getId());
        }
        return teacher;
    }


    /**
     * 读取账户对应的教师信息
     * @return
     */
    public SchoolStudent getLoginStudent(){
        SchoolStudent student=null;
        //获取当前登录信息
        SysUser sysUser = UserUtil.getLoginUser();
        if(sysUser.getId()!=null){
            student=schoolStudentMapper.getByUserId(sysUser.getId());
        }
        return student;
    }

    /**
     * 读取账户对应的学生信息
     * @param sysUser
     * @return
     */
    public SchoolStudent getStudent(@NotNull(message = "用户信息不能为空") SysUser sysUser){
        SchoolStudent student=null;
        if(sysUser.getId()!=null){
            student=schoolStudentMapper.getByUserId(sysUser.getId());
        }
        return student;
    }

    public SchoolStudent getStudentByUserId(@NotNull(message = "用户id不能为空") Long userId){
        return schoolStudentMapper.getByUserId(userId);
    }

    /**
     * 验证用户是否有课堂的参与权限（即聊天权限）
     * @param lessonId
     */
    public void validateHaveLessonsAuthority(@NotNull(message = "课堂主键不能为空")String lessonId,@NotNull(message = "用户主键不能为空") Long userId){
        //获取当前登录信息
//        SysUser sysUser = UserUtil.getLoginUser();
        //获取当前登录账户对应的教师信息
        SchoolTeacher teacher=this.getTeacherByUserId(userId);
        //从课堂中读取教学任务/教学班级信息
        SchoolTeachingTaskLesson lesson = schoolTeachingTaskLessonMapper.findById(lessonId);
        if(teacher!=null){
            //检查该教师是否有该课堂对应的教学任务  是这个课堂对应教学任务下的老师 只有教学任务教师表里有该教师才能访问
            log.info(lesson.getTaskId()+"tesaaa"+teacher.getId());
            if(!schoolTeachingTaskLessonMapper.isTaskTeacherByTeacherId(lesson.getTaskId(), teacher.getId())){
                throw new MyForbiddenException("操作失败：该教师不是本教学班教师");
            }
        }else{//如果不是教师，就检查是否为学生
            SchoolStudent student=schoolStudentMapper.getByUserId(userId);
            if(student==null){
                throw new MyForbiddenException("操作失败：只有学生才可以操作");
            }
            //判断该学生是否是该教学班级的学生
            if(!schoolTeachingTaskLessonMapper.isTaskStudentByStudentId(lesson.getTaskId(), student.getId())){
                throw new MyForbiddenException("操作失败：该学生无法不是本教学班学生");
            }
        }
    }

    /**
     * 验证教师是否拥有该课程的管理权限
     * 说明：
     * 1.根据学校模块的配置决定课程的管理权限
     * @param courseId
     */
    public void validateCourseManageAuthorityOfLoginTeacher(Serializable courseId){
        if(courseId==null){
            throw new MyForbiddenException("操作失败：课程id不能为空");
        }
        //获取当前登录信息
        SysUser sysUser = UserUtil.getLoginUser();
        if (sysUser != null) {//如果当前登录账户存在
            //获取当前登录账户对应的教师信息
            Long teacherId = schoolTeacherMapper.getIdByUserId(sysUser.getId());
            if(teacherId==null){
                throw new MyForbiddenException("操作失败：只有教师才可以操作");
            }
            //读取学校配置信息
            SchoolConfig schoolConfig = schoolConfigMapper.getEnableSchoolConfig();
            if(schoolConfig.getAllowAssistManageCourse()){//如果允许科任教师协助管理课程内容
                if(schoolTeacherCourseMapper.countCourseAndCourseOfTeachingtaskByTeacherId(courseId,teacherId)==0){
                    throw new MyForbiddenException("操作失败：您没有该课程的管理权限");
                }
            }else{//否则只有课程负责人可以对课程内容进行管理
                if(schoolTeacherCourseMapper.countByCourseIdAndTeacherId(courseId,teacherId)==0){
                    throw new MyForbiddenException("操作失败：您没有该课程的管理权限");
                }
            }
        }
    }
}
